<?php

namespace App\Models;
use App\Models\Common\Constant;
use App\Models\ResourceModel\Users;
use Illuminate\Support\Facades\DB;

class CloudhouseWarehouseModel extends BaseModel
{
    const CLOUDHOUSE_WAREHOUSE_TYPE = [
        1 => '本地仓',
        2 => '第三方仓',
        3 => '虚拟仓'
    ];
    const WAREHOUSE_LOCATION_TYPE = [
        1 => '地面库位',
        2 => '货架库位'
    ];
    protected $cloudhouseWarehouseModel;
    protected $cloudhouseWarehouseLocationModel;
    protected $usersModel;
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $this->cloudhouseWarehouseModel = new \App\Models\ResourceModel\CloudhouseWarehouse();
        $this->cloudhouseWarehouseLocationModel = new \App\Models\ResourceModel\CloudhouseWarehouseLocation();
        $this->usersModel = new Users();
    }

    public function saveCloudhouseWarehouse($params = [])
    {
        try {
            // 1、校验参数
            $this->_filterSaveCloudhouseWarehouse($params);
            // 2、判断新增或更新
            $warehouseId = $params['id'];
            if (empty($warehouseId)){
                $warehouseId = $this->cloudhouseWarehouseModel::query()
                    ->insertGetId($params);
            }else{
                $this->cloudhouseWarehouseModel::query()
                    ->where('id', $warehouseId)
                    ->update($params);
            }

            return ['code' => 200, 'msg' => '保存成功！', 'data' => $warehouseId];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => $e->getMessage()];
        }
    }

    /**
     * @Desc:过滤参数
     * @param $params
     * @throws \Exception
     * @author: Liu Sinian
     * @Time: 2023/3/22 11:25
     */
    private function _filterSaveCloudhouseWarehouse(&$params)
    {
        if (!isset($params['id']) || empty($params['id'])){
            $params['id'] = 0;
            $params['created_at'] = date('Y-m-d H:i:s');
        }else{
            $params['updated_at'] = date('Y-m-d H:i:s');
        }
        if (!isset($params['warehouse_type']) || empty(self::CLOUDHOUSE_WAREHOUSE_TYPE[$params['warehouse_type']] ?? '')){
            throw new \Exception('仓库类型未设置！');
        }
        if (isset($params['user_id'])){
            $userMdl = $this->usersModel::query()
                ->where('Id', $params['user_id'])
                ->first();
            if (!empty($userMdl)){
                $params['user_name'] = $userMdl->account;
                $params['phone'] = $userMdl->phone;
            }
        }
//        // 库位面积
//        if (!isset($params['warehouse_area']) || $params['warehouse_area'] < 0){
//            $params['warehouse_area'] = 0;
//        }
//        // 库位容量
//        if (!isset($params['warehouse_capacity']) || $params['warehouse_capacity'] < 0){
//            $params['warehouse_capacity'] = 0;
//        }
        // 过滤非表字段数据
        $params = $this->allowField($params, 'cloudhouse_warehouse');
    }

    public function getCloudhouseWarehouseList($params = [])
    {
        $cloudhouseWarehouse = $this->cloudhouseWarehouseModel::query();
        // 仓库名称
        if (isset($params['warehouse_name']) && !empty($params['warehouse_name'])){
            $cloudhouseWarehouse->where('warehouse_name', 'like', '%'.$params['warehouse_name'].'%');
        }
        // 仓库类型
        if (isset($params['warehouse_type']) && !empty($params['warehouse_type'])){
            $cloudhouseWarehouse->whereIn('warehouse_type', $params['warehouse_type']);
        }
        // 仓库编码
        if (isset($params['warehouse_code']) && !empty($params['warehouse_code'])){
            $cloudhouseWarehouse->where('warehouse_code', 'like', '%'.$params['warehouse_code'].'%');
        }
        // 负责人
        if (isset($params['user_id']) && !empty($params['user_id'])){
            $cloudhouseWarehouse->where('user_id', $params['user_id']);
        }
        // 创建时间
        if (isset($params['created_at']) && !empty($params['created_at'])){
            $cloudhouseWarehouse->whereBetween('created_at', $params['created_at']);
        }
        $count = $cloudhouseWarehouse->count();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 30;
        $pagenum = $page <= 1 ? 0 : ($page-1)*$limit;
        $list = $cloudhouseWarehouse->limit($limit)
            ->offset($pagenum)
            ->orderByRaw("FIELD(warehouse_type, " . implode(", ", [1, 3, 2]) . ")")
            ->orderBy('id')
            ->get();
        foreach ($list as $item){
            if($item->id == 1){
                $item->warehouse_inventory = DB::table('self_custom_sku')->sum('tongan_inventory');
            }elseif ($item->id == 2){
                $item->warehouse_inventory = DB::table('self_custom_sku')->sum('quanzhou_inventory');
            }elseif ($item->id == 3){
                $item->warehouse_inventory = DB::table('self_custom_sku')->sum('cloud_num');
            }elseif ($item->id == 4){
                $item->warehouse_inventory = DB::table('self_custom_sku')->sum('factory_num');
            }elseif ($item->id == 6){
                $item->warehouse_inventory = DB::table('self_custom_sku')->sum('deposit_inventory');
            } elseif ($item->id == 21){
                $item->warehouse_inventory = DB::table('self_custom_sku')->sum('direct_inventory');
            }

            $item->warehouse_type_name = self::CLOUDHOUSE_WAREHOUSE_TYPE[$item->warehouse_type] ?? '';
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $list]];
    }

    /**
     * @Desc:保存库位
     * @param $params
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/3/22 16:19
     */
    public function saveCloudhouseWarehouseLocation($params = [])
    {
        try {
            // 1、校验参数
            $this->_filterSaveCloudhouseWarehouseLocation($params);
            // 2、判断新增或更新
            $locationId = $params['id'];
            DB::beginTransaction();
            if (empty($locationId)){
                $locationId = $this->cloudhouseWarehouseLocationModel::query()
                    ->insertGetId($params);
            }else{
                $this->cloudhouseWarehouseLocationModel::query()
                    ->where('id', $locationId)
                    ->update($params);
            }
//            // 3、更新仓库信息
//            $locationMdl = $this->cloudhouseWarehouseLocationModel::query()
//                ->where('warehouse_id', $params['warehouse_id'])
//                ->select('location_area', 'location_capacity')
//                ->get();
//            if ($locationMdl->isNotEmpty()){
//                $locationMdl = $locationMdl->toArray();
//                $area = array_sum(array_column($locationMdl, 'location_area'));
//                $capacity = array_sum(array_column($locationMdl, 'location_capacity'));
//                $saveWarehouse = [
//                    'id' => $params['warehouse_id'],
//                    'warehouse_area' => $area,
//                    'warehouse_capacity' => $capacity
//                ];
//                $this->saveCloudhouseWarehouse($saveWarehouse);
//            }

            DB::commit();
            return ['code' => 200, 'msg' => '保存成功！', 'data' => $locationId];
        }catch (\Exception $e){
            DB::rollBack();
            return ['code' => 500, 'msg' => $e->getMessage()];
        }
    }

    /**
     * @Desc: 库位保存数据校验及处理
     * @param $params
     * @throws \Exception
     * @author: Liu Sinian
     * @Time: 2023/3/22 16:05
     */
    private function _filterSaveCloudhouseWarehouseLocation(&$params)
    {
        // 关联仓库
        if (!isset($params['warehouse_id']) || empty($params['warehouse_id'])){
            throw new \Exception('未绑定仓库！');
        }
        // 库位类型
        if (!isset($params['location_type']) || empty(self::WAREHOUSE_LOCATION_TYPE[$params['location_type']])){
            throw new \Exception('未设置库位类型！');
        }
        // 层级
        if (!isset($params['level']) || empty($params['level'])){
            throw new \Exception('未设置层级！');
        }
        // 平台
        if (isset($params['platform_ids']) && !empty($params['platform_ids'])){
            $platformMdl = DB::table('platform')->whereIn('identifying', $params['platform_ids'])->get();
            $platformMdl = json_decode(json_encode($platformMdl), true);
            $platformName = array_column($platformMdl, 'name');
            $platformIds = json_encode(array_column($platformMdl, 'identifying'));
            $params['platform_name'] = implode(',', $platformName);
            $params['platform_ids'] = $platformIds;
        }
        if (isset($params['id']) && !empty($params['id'])){
            $params['updated_at'] = date('Y-m-d H:i:s');
        }else{
//            if ($params['level'] > 2){
//                throw new \Exception('不可设置第二层级以下库位！');
//            }
            // 新增时增加库位编码及库位序号
            $params['id'] = 0;
            $params['created_at'] = date('Y-m-d H:i:s');
            // 层级为1，特殊处理
            if ($params['level'] == 1){
                $locationMdl = $this->cloudhouseWarehouseLocationModel::query()
                    ->where('warehouse_id', $params['warehouse_id'])
                    ->where('level', 1)
                    ->orderBy('location_no', 'desc')
                    ->first();
                // 是否有同级数据，取序号最大的那条
                if (!empty($locationMdl)){
                    // 库位序号
                    $locationNo = $locationMdl->location_no + 1;
                    $params['location_no'] = $locationNo;
                    if (($locationNo + 64) > 90){
                        $locationCode = $locationNo + 70; // a
                    }else{
                        $locationCode = $locationNo + 64; // A
                    }
                    if (!($locationCode>=65 && $locationCode<=90 || $locationCode>=97 && $locationCode<=122)){ // 判断是否在A-Z 或 a-z之间
                        throw new \Exception('第一层级库位编码超出预设值！');
                    }
                    // 库位编码
                    $params['location_code'] = chr($locationCode);
                    // 库位排序
                    $params['sort'] = $locationMdl->sort+1;
                }else{
                    $params['location_no'] = 1;
                    $params['location_code'] = 'A';
                    // 库位排序
                    $params['sort'] = 1;
                }
            }else{
                if (!isset($params['fid']) || empty($params['fid'])){
                    throw new \Exception('未绑定上一层级！');
                }else{
                    // 平台
                    if ($params['level'] > 2){
                        if (!isset($params['platform_ids']) || empty($params['platform_ids'])){
                            throw new \Exception('未设置平台！');
                        }
                    }

                    // 获取上级库位信息
                    $fLocationMdl = $this->cloudhouseWarehouseLocationModel::query()
                        ->where('id', $params['fid'])
                        ->select()
                        ->first();
                    if (empty($fLocationMdl)){
                        throw new \Exception('无上级库位数据！');
                    }
                    $locationMdl = $this->cloudhouseWarehouseLocationModel::query()
                        ->where('level', $params['level'])
                        ->where('fid', $params['fid'])
                        ->orderBy('location_no', 'desc')
                        ->first();
                    if (!empty($locationMdl)){
                        $params['location_no'] = $locationMdl->location_no + 1;
                    }else{
                        $params['location_no'] = 1;
                    }
                    if ($params['level'] == 2){
                        // 库位编码 eg. A01、A03、B02
                        $params['location_code'] = $fLocationMdl->location_code . str_pad($params['location_no'], '2', '0', STR_PAD_LEFT);
                        $params['sort'] = $fLocationMdl->sort;
                        if (!empty($locationMdl)){
                            $params['sort2'] = $locationMdl->sort2+1;
                        }else{
                            $params['sort2'] = 1;
                        }
                    }
                    if ($params['level'] == 3){
                        // 库位编码 eg. A01-001、B01-002、A02-003
                        $params['location_code'] = $fLocationMdl->location_code . '-' . str_pad($params['location_no'], '3', '0', STR_PAD_LEFT);
                        $params['sort'] = $fLocationMdl->sort;
                        $params['sort2'] = $fLocationMdl->sort2 ?? 0;
                        if (!empty($locationMdl)){
                            $params['sort3'] = $locationMdl->sort3+1;
                        }else{
                            $params['sort3'] = 1;
                        }
                    }

                }
            }
        }
//        // 库位面积
//        if (!isset($params['location_area']) || $params['location_area'] < 0){
//            $params['location_area'] = 0;
//        }
//        // 库位容量
//        if (!isset($params['location_capacity']) || $params['location_capacity'] < 0){
//            $params['location_capacity'] = 0;
//        }
        // 过滤非表字段数据
        $params = $this->allowField($params, 'cloudhouse_warehouse_location');
    }

    public function getCloudhouseWarehouseLocationList($params)
    {
        $cloudhouseWarehouseLocation = $this->cloudhouseWarehouseLocationModel::query()
            ->leftJoin('cloudhouse_warehouse as a', 'cloudhouse_warehouse_location.warehouse_id', '=', 'a.id');
        // 仓库
        if (isset($params['warehouse_id']) && !empty($params['warehouse_id'])){
            $cloudhouseWarehouseLocation->whereIn('cloudhouse_warehouse_location.warehouse_id', $params['warehouse_id']);
        }
        // 仓库名称
        if (isset($params['warehouse_name']) && !empty($params['warehouse_name'])){
            $cloudhouseWarehouseLocation->where('a.warehouse_name', 'like', '%'.$params['warehouse_name'].'%');
        }
        // 仓库类型
        if (isset($params['warehouse_type']) && !empty($params['warehouse_type'])){
            $cloudhouseWarehouseLocation->whereIn('a.warehouse_type', $params['warehouse_type']);
        }
        // 仓库编码
        if (isset($params['warehouse_code']) && !empty($params['warehouse_code'])){
            $cloudhouseWarehouseLocation->where('a.warehouse_code', 'like', '%'.$params['warehouse_code'].'%');
        }
        // 负责人
        if (isset($params['user_id']) && !empty($params['user_id'])){
            $cloudhouseWarehouseLocation->where('a.user_id', $params['user_id']);
        }
        // 创建时间
        if (isset($params['created_at']) && !empty($params['created_at'])){
            $cloudhouseWarehouseLocation->whereBetween('cloudhouse_warehouse_location.created_at', $params['created_at']);
        }
        // 库位名称
        if (isset($params['location_name']) && !empty($params['location_name'])){
            $cloudhouseWarehouseLocation->where('cloudhouse_warehouse_location.location_name', '%'.$params['location_name'].'%');
        }
        // 库位类型
        if (isset($params['location_type']) && !empty($params['location_type'])){
            $cloudhouseWarehouseLocation->where('cloudhouse_warehouse_location.location_type', $params['location_type']);
        }
        // 库位编码
        if (isset($params['location_code']) && !empty($params['location_code'])){
            $cloudhouseWarehouseLocation->where('cloudhouse_warehouse_location.location_code', '%'.$params['location_code'].'%');
        }
        // 库位层级
        if (isset($params['level']) && !empty($params['level'])){
            $cloudhouseWarehouseLocation->where('cloudhouse_warehouse_location.level', $params['level']);
        }
        // 上级库位id
        if (isset($params['fid']) && !empty($params['fid'])){
            $cloudhouseWarehouseLocation->where('cloudhouse_warehouse_location.fid', $params['fid']);
        }
        // 平台
        if (isset($params['platform_id']) && !empty($params['platform_id'])){
            $cloudhouseWarehouseLocation->where('cloudhouse_warehouse_location.platform_ids', 'like', '%'.$params['platform_id'].'%');
        }
        $count = $cloudhouseWarehouseLocation->count();

        if (isset($params['limit']) || isset($params['page'])){
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 30;
            $pagenum = $page <= 1 ? 0 : ($page-1)*$limit;
            $cloudhouseWarehouseLocation->limit($limit)
                ->offset($pagenum)
                ->orderBy('cloudhouse_warehouse_location.sort', 'asc')
                ->orderBy('cloudhouse_warehouse_location.sort2', 'asc')
                ->orderBy('cloudhouse_warehouse_location.sort3', 'asc');
        }
        $list = $cloudhouseWarehouseLocation->get(['a.*', 'cloudhouse_warehouse_location.*']);
        // 是否为列表
        if (isset($params['is_list']) && $params['is_list'] == 1){
            $all = $this->cloudhouseWarehouseLocationModel::all();
            $stockMdl = DB::table('cloudhouse_location_num as a')
                ->leftJoin('cloudhouse_warehouse_location as b', 'a.location_id', '=', 'b.id')
                ->get();
            foreach ($list as $item){
                $item->location_type_name = self::WAREHOUSE_LOCATION_TYPE[$item->location_type] ?? '';
                $item->warehouse_type_name = self::CLOUDHOUSE_WAREHOUSE_TYPE[$item->warehouse_type] ?? '';
                $item->hasChild = false;
                foreach ($all as $_item){
                    if ($item['id'] == $_item['fid']){
                        $item->hasChild = true;
                    }
                }
                $item->total_stock_num = 0;
                $item->total_lock_stock_num = 0;
                $item->total_acount = 0.00;
                // 所有的
                $locationIds = [];
                if ($item->level == 1){
                    $item->level_name = '一级库位';
                    $item->platform_ids = json_decode($item->platform_ids) ?? [];
                    foreach ($all as $a){
                        if ($a->fid == $item->id){
                            $locationIds[] = $a->id;
                        }
                    }
                    foreach ($all as $a){
                        if (in_array($a->fid, $locationIds)){
                            $locationIds[] = $a->id;
                        }
                    }
                    $locationIds[] = $item->id;
                }
                if ($item->level == 2){
                    $item->level_name = '二级库位';
                    $item->platform_ids = json_decode($item->platform_ids) ?? [];
                    foreach ($all as $a){
                        if ($a->fid == $item->id){
                            $locationIds[] = $a->id;
                        }
                    }
                    $locationIds[] = $item->id;
                }
                if ($item->level == 3){
                    $item->level_name = '三级库位';
                    $item->platform_ids = json_decode($item->platform_ids) ?? [];
                    $locationIds[] = $item->id;
                }

                foreach ($stockMdl as $stock){
                    if (in_array($stock->location_id, $locationIds)){
                        $item->total_stock_num += $stock->num;
                        $item->total_lock_stock_num += $stock->lock_num;
//                        $item->total_acount +=  $stock->num * $this->GetCloudHousePrice($stock->warehouse_id, $stock->custom_sku_id);
                        $item->total_acount = 0;
                    }
                }
            }
        }else{
            $level_first = array();
            $level_second = array();
            $level_third = array();
            $list = $list->toArray();
            foreach ($list as $item){
                if ($item['level'] == 1){
                    $level_first[] = $item;
                }elseif ($item['level'] == 2){
                    $level_second[] = $item;
                }elseif ($item['level'] == 3){
                    $level_third[] = $item;
                }
            }
            foreach ($level_second as &$v){
                $child = array();
                foreach ($level_third as &$_v){
                    if ($_v['fid'] == $v['id']){
                        $child[] = $_v;
                    }
                }
                if (!empty($child)){
                    $v['child'] = $child;
                }
            }
            foreach ($level_first as &$v){
                $child = array();
                foreach ($level_second as &$_v){
                    if ($_v['fid'] == $v['id']){
                        $child[] = $_v;
                    }
                }
                if (!empty($child)){
                    $v['child'] = $child;
                }
            }
            $list = $level_first;
            $count = count($list);
        }
        
        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $list]];
    }


    public function deleteCloudhouseWarehouse($params)
    {
        try {
            if (!isset($params['id']) || empty($params['id'])){
                throw new \Exception('未给定仓库标识！');
            }
            DB::beginTransaction();
            $delete = $this->cloudhouseWarehouseModel::query()
                ->whereIn('id', $params['id'])
                ->delete();
            $this->cloudhouseWarehouseLocationModel::query()
                ->whereIn('warehouse_id', $params['id'])
                ->delete();

            DB::commit();
            return ['code' => 200, 'msg' => '删除成功！', 'data' => $delete];
        }catch (\Exception $e){
            DB::rollback();
            return ['code' => 500, 'msg' => '删除失败！原因：'. $e->getMessage()];
        }
    }

    public function deleteCloudhouseWarehouseLocation($params)
    {
        try {
            if (!isset($params['id']) || empty($params['id'])){
                return ['code' => 500, 'msg' => '未给定仓库标识！'];
            }
            if (!isset($params['level']) || empty($params['level'])){
                return ['code' => 500, 'msg' => '未给定库位层级！'];
            }
            $ids = [];
            switch ($params['level']){
                case 1:
                    $locationMdl = $this->cloudhouseWarehouseLocationModel::query()
                        ->where('fid', $params['id'])
                        ->get();
                    if (!empty($locationMdl)){
                        $ids = array_column($locationMdl->toArray(), 'id');

                        $locationMdl = $this->cloudhouseWarehouseLocationModel::query()
                            ->whereIn('fid', $ids)
                            ->get();
                        $ids = array_merge($ids, array_column($locationMdl->toArray(), 'id'));
                        array_push($ids, (int)$params['id']);

                    }else{
                        array_push($ids, (int)$params['id']);
                    }
                    break;
                case 2:
                    $locationMdl = $this->cloudhouseWarehouseLocationModel::query()
                        ->where('fid', $params)
                        ->get();
                    if (!empty($locationMdl)){
                        $ids = array_column($locationMdl->toArray(), 'id');
                        array_push($ids, (int)$params['id']);
                    }else{
                        array_push($ids, (int)$params['id']);
                    }
                    break;
                case 3:
                    array_push($ids, (int)$params['id']);
                    break;
                default:
                    throw new \Exception('库位层级非预设值！');
            }
            $delete = $this->cloudhouseWarehouseLocationModel::query()
                ->whereIn('id', $ids)
                ->delete();
            if ($delete){
                return ['code' => 200, 'msg' => '删除成功！', 'data' => $delete];
            }else{
                return ['code' => 500, 'msg' => '删除失败！'];
            }
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '删除失败！原因：'. $e->getMessage()];
        }
    }


    public function getCloudhouseWarehouseLocationStockList($params)
    {
        $list = db::table('self_custom_sku')->where('tongan_inventory','>',0);
        $limit = $params['limit'] ?? 30;
        $page = $params['page'] ?? 1;
        $offset = $limit * ($page-1);

          
        

        if(isset($params['custom_sku'])){
            $list = $list->where('custom_sku','like','%'.$params['custom_sku'].'%')->orwhere('old_custom_sku','like','%'.$params['custom_sku'].'%');
        }
        $count = $list->count();
       
        $list = $list->select('custom_sku','old_custom_sku','tongan_inventory as intsock_num','id as custom_sku_id')->orderby('tongan_inventory','desc')->limit($limit)->offset($offset)->get();

        foreach ($list as $v) {
            # code...
            if(!empty($v->old_custom_sku)){
                $v->custom_sku = $v->old_custom_sku;
            }

            $v->warehouse_name = '国内仓';
        }
        return ['count' => $count, 'list' => $list];
    }

    /**
     * @Desc:获取库位库存列表
     * @param $params
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/5/3 11:29
     */
    public function getCloudhouseWarehouseLocationStockListOld($params)
    {
        $stockMdl = DB::table('cloudhouse_location_num as a')
            ->leftJoin('cloudhouse_warehouse_location as b', 'a.location_id', '=', 'b.id')
            ->leftJoin('cloudhouse_warehouse as c', 'b.warehouse_id', '=', 'c.id')
            ->leftJoin('platform as d', 'a.platform_id', '=', 'd.Id');
        if (isset($params['warehouse_id']) && !empty($params['warehouse_id'])){
            if (is_array($stockMdl)){
                $stockMdl = $stockMdl->whereIn('c.id', $params['warehouse_id']);
            }else{
                $stockMdl = $stockMdl->where('c.id', $params['warehouse_id']);
            }

        }
        if (isset($params['warehouse_location_id']) && !empty($params['warehouse_location_id'])){
            if (!is_array($params['warehouse_location_id'])){
                $params['warehouse_location_id'] = [$params['warehouse_location_id']];
            }
            $locationIds = [];
            $locationMdl = db::table('cloudhouse_warehouse_location')->whereIn('id', $params['warehouse_location_id'])->get();
            $locationAll = db::table('cloudhouse_warehouse_location')->get();
            $fid = [];
            foreach ($locationMdl as $item){
                if ($item->level == 1){
                    foreach ($locationAll as $all){
                        if ($item->id == $all->fid){
                            $fid[] = $all->id;
                        }
                    }

                }
                else if ($item->level == 2){
                    foreach ($locationAll as $all){
                        if ($item->id == $all->fid){
                            $locationIds[] = $all->id;
                        }
                    }
                }
                else if ($item->level == 3){
                    $locationIds[] = $item->id;
                }
            }
            $fid = array_unique($fid);
            foreach ($fid as $item){
                foreach ($locationAll as $all){
                    if ($item == $all->fid){
                        $locationIds[] = $all->id;
                    }
                }
            }
            $stockMdl = $stockMdl->whereIn('b.id', $locationIds);
        }
        if(isset($params['location_code'])){
            $stockMdl = $stockMdl->where('b.location_code', $params['location_code']);
        }
        if(isset($params['location_type'])){
            $stockMdl = $stockMdl->where('b.type', $params['location_type']);
        }
        if (isset($params['custom_sku']) && !empty($params['custom_sku'])){
            $customSkuMdl = db::table('self_custom_sku')->where('custom_sku', 'like', '%'.$params['custom_sku'].'%')->orWhere('old_custom_sku', 'like', '%'.$params['custom_sku'].'%')->get();
            $customSkuMdl = json_decode(json_encode($customSkuMdl), true);
            $customSkuId = array_column($customSkuMdl, 'id');
            $stockMdl = $stockMdl->whereIn('a.custom_sku_id', $customSkuId);
        }

        if (isset($params['custom_skus']) && !empty($params['custom_skus'])) {
            $customSkuArr   = explode(',', $params['custom_skus']);
            $customSkuIdArr = [];
            foreach ($customSkuArr as $customSku) {
                $customSkuId = DB::table('self_custom_sku')
                    ->where('custom_sku', $customSku)
                    ->orwhere('old_custom_sku', $customSku)
                    ->value('id');
                if ($customSkuId) {
                    $customSkuIdArr[] = $customSkuId;
                }
            }
            if (!$customSkuIdArr) {
                return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => 0, 'list' => []]];
            }

            $stockMdl->whereIn('a.custom_sku_id', $customSkuIdArr);
        }

        if (isset($params['spu']) && !empty($params['spu'])){
            $stockMdl = $stockMdl->whereIn('a.spu_id', $params['spu']);
        }
        if (isset($params['platform_id']) && !empty($params['platform_id'])){
            $stockMdl = $stockMdl->where('d.id', $params['platform_id']);
        }

        if(isset($params['is_zero']) && !empty($params['is_zero'])){
            if($params['is_zero']==1){
                $stockMdl = $stockMdl->where('a.num','>',0);
            }
        }
        $count = $stockMdl->count();
        $limit = $params['limit'] ?? 30;
        $page = $params['page'] ?? 1;
        $offset = $limit * ($page-1);
        $postType = $params['posttype'] ?? 1;
        if ($postType != 2) {
            $stockMdl->limit($limit)->offset($offset);
        }

        if (isset($customSkuIdArr)) {
            $customSkuIdStr = implode(',', $customSkuIdArr);
            $stockMdl->orderByRaw("find_in_set(a.custom_sku_id, '{$customSkuIdStr}')");
        }

        $stockMdl = $stockMdl
            ->orderBy('custom_sku_id', 'DESC')
            ->select('a.*', 'b.location_name', 'c.warehouse_name', 'b.location_code', 'd.name as platform_name','b.type as location_type')->get()->toArray();

        if ($postType == 2) {
            if(count($stockMdl)>1000){
                return ['type' => 'fail', 'msg' => '此表不能导出超过1000条数据'];
            }
        }

        $customSkuCountMdl = db::table('custom_sku_count')->where('is_del', 0)->where('is_instore', 1)->get();
        $platform = DB::table('platform')->pluck('name', 'id');

        $spu_ids = [];
        $custom_sku_ids = [];
        $location_ids = [];
        $platform_ids = [];
        foreach ($stockMdl as $st){
            if(!in_array($st->spu_id,$spu_ids)){
                $spu_ids[] = $st->spu_id;
            }
            if(!in_array($st->custom_sku_id,$custom_sku_ids)){
                $custom_sku_ids[] = $st->custom_sku_id;
            }
            if(!in_array($st->location_id,$location_ids)){
                $location_ids[] = $st->location_id;
            }
            if(!in_array($st->platform_id,$platform_ids)){
                $platform_ids[] = $st->platform_id;
            }
        }
        $inventoryDetail = $this->batchInventoryDetailByWlp($custom_sku_ids, [], $location_ids, $platform_ids);

        $spuList = db::table('self_spu')->select('id', 'spu', 'old_spu')->whereIn('id', $spu_ids)->get()->keyBy('id');
        $customSkuList = db::table('self_custom_sku')
            ->select('id', 'custom_sku', 'old_custom_sku')
            ->whereIn('id', $custom_sku_ids)
            ->get()
            ->keyBy('id');


        foreach ($stockMdl as $v) {
            # code...
            $cus               = $this->GetCustomSkus($v->custom_sku);
            $v->old_custom_sku = $cus['old_custom_sku'];
            $v->platform_name  = $platform[$v->platform_id] ?? '';
            $v->spu            = $spuList[$v->spu_id]->old_spu ?: $spuList[$v->spu_id]->spu;
            $v->custom_sku     = $customSkuList[$v->custom_sku_id]->old_custom_sku ?: $customSkuList[$v->custom_sku_id]->custom_sku;


            $inventory      = $inventoryDetail[$v->custom_sku_id . '_' . $v->location_id . '_' . $v->platform_id] ??
                ['shelf_num' => 0, 'lock_num' => 0, 'delist_num' => 0,];
            $v->intsock_num = $v->num - $inventory['lock_num'] - $inventory['shelf_num'];//可用库存
            $v->lock_num    = $inventory['lock_num'];//锁定库存
            $v->shelf_num   = $inventory['shelf_num'];//待入库库存
            $v->delist_num  = $inventory['delist_num'];//已拣货库存
            $boxNo          = [];
            foreach ($customSkuCountMdl as $item) {
                if ($v->location_code == $item->location_code && $v->custom_sku_id == $item->custom_sku_id) {
                    $boxNo[] = [
                        'no'  => $item->no,
                        'num' => $item->count
                    ];
                }
            }
            $v->boxNo = $boxNo;
        }

        if ($postType == 2) {

            $p['title']='库位库存导出表'.time();
            $list = [
                'warehouse_name' => '仓库名称',
                'location_name'  => '库位名称',
                'location_type'  => '库位类型',
                'platform_name'  => '平台',
                'custom_sku'     => '库存SKU	',
                'spu'            => 'spu',
                'num'            => '库存',
                'lock_num'       => '锁定库存',
                'intsock_num'    => '可用库存',
                'shelf_num'      => '待入库库存',
                'delist_num'     => '已拣货库存',
            ];

            $p['title_list']  = $list;
            $p['data'] =  $stockMdl;
            $find_user_id = $params['find_user_id']??1;
            $p['user_id'] = $find_user_id;
            $p['type'] = '库存管理-库位库存导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];

        }

        return ['count' => $count, 'list' => $stockMdl];
    }

    /**
     * @Desc:获取库位库存变动日志列表
     * @param $params
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/5/3 11:29
     */
    public function getCloudhouseWarehouseLocationLogList($params)
    {
        $stockLogMdl = DB::table('cloudhouse_location_log as a')
            ->leftJoin('cloudhouse_warehouse_location as b', 'a.location_id', '=', 'b.id')
            ->leftJoin('cloudhouse_warehouse as c', 'b.warehouse_id', '=', 'c.id')
            ->leftJoin('platform as d', 'a.platform_id', '=', 'd.Id');
        if (isset($params['warehouse_id']) && !empty($params['warehouse_id'])){
            $stockLogMdl = $stockLogMdl->whereIn('c.id', $params['warehouse_id']);
        }
        if (isset($params['warehouse_location_id']) && !empty($params['warehouse_location_id'])){
            $locationIds = [];
            $locationMdl = db::table('cloudhouse_warehouse_location')->whereIn('id', $params['warehouse_location_id'])->get();
            $locationAll = db::table('cloudhouse_warehouse_location')->get();
            $fid = [];
            foreach ($locationMdl as $item){
                if ($item->level == 1){
                    foreach ($locationAll as $all){
                        if ($item->id == $all->fid){
                            $fid[] = $all->id;
                        }
                    }

                }
                else if ($item->level == 2){
                    foreach ($locationAll as $all){
                        if ($item->id == $all->fid){
                            $locationIds[] = $all->id;
                        }
                    }
                }
                else if ($item->level == 3){
                    $locationIds[] = $item->id;
                }
            }
            $fid = array_unique($fid);
            foreach ($fid as $item){
                foreach ($locationAll as $all){
                    if ($item == $all->fid){
                        $locationIds[] = $all->id;
                    }
                }
            }
            $stockLogMdl = $stockLogMdl->whereIn('b.id', $locationIds);
        }
        if (isset($params['custom_sku']) && !empty($params['custom_sku'])){
//            $customSku = explode(',', $params['custom_sku']);
//            $customSkuMdl = db::table('self_custom_sku')->where(function ($q) use ($customSku){
//               foreach ($customSku as $c){
//                   $q->whereOr('custom_sku', '%'.$c.'%')
//                       ->whereOr('old_custom_sku', '%'.$c.'%');
//               }
//               return $q;
//            })->get(['Id'])->toArrayList();
//            $customSkuIds = array_column($customSkuMdl, 'Id');
//            $stockLogMdl = $stockLogMdl->whereIn('a.custom_sku_id', $customSkuIds);
            $customSkuId = $this->GetCustomSkuId($params['custom_sku']);
            $stockLogMdl = $stockLogMdl->where('a.custom_sku_id', $customSkuId);
        }
        if (isset($params['spu']) && !empty($params['spu'])){
            $stockLogMdl = $stockLogMdl->whereIn('a.spu_id', $params['spu']);
        }
        if (isset($params['user_id']) && !empty($params['user_id'])){
            $stockLogMdl = $stockLogMdl->whereIn('a.user_id', $params['user_id']);
        }
        if (isset($params['type']) && !empty($params['type'])){
            $stockLogMdl = $stockLogMdl->where('a.type', $params['type']);
        }
        if (isset($params['order_no']) && !empty($params['order_no'])){
            $stockLogMdl = $stockLogMdl->where('a.order_no', 'like', '%'.$params['order_no'].'%');
        }
        if (isset($params['time']) && !empty($params['time'])){
            $stockLogMdl = $stockLogMdl->whereBetween('a.time', $params['time']);
        }
        if (isset($params['box_code']) && !empty($params['box_code'])){
            $boxMdl = db::table('goods_transfers_box')->where('box_code', 'like', '%'.$params['box_code'].'%')->get();
            $boxMdl = json_decode(json_encode($boxMdl), true);
            $orderNos = array_column($boxMdl, 'order_no');
            $stockLogMdl = $stockLogMdl->whereIn('a.order_no', $orderNos);
        }
        if (isset($params['platform_id']) && !empty($params['platform_id'])){
            $stockLogMdl = $stockLogMdl->where('a.platform_id', $params['platform_id']);
        }
        $count = $stockLogMdl->count();
        $limit = $params['limit'] ?? 30;
        $page = $params['page'] ?? 1;
        $offset = $limit * ($page-1);
        $stockLogMdl = $stockLogMdl->limit($limit)
            ->offset($offset)
            ->orderBy('time', 'DESC')
            ->get(['a.*', 'b.location_name', 'c.warehouse_name', 'b.location_code', 'a.platform_id', 'd.name as platform_name']);
        foreach ($stockLogMdl as $item){
            $item->user_name = $this->GetUsers($item->user_id)['account'] ?? '';
            $item->type_name = Constant::WAREHOUSE_LOCATION_LOG_TYPE_NAME[$item->type] ?? '';
            $item->platform_name = $item->platform_name ?? '';
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $stockLogMdl]];
    }

    public function moveWarehouseLocationInventory($params)
    {
        try {
            $params = $this->_checkMoveWarehouseLocationInventoty($params);
            db::beginTransaction();
            $memo = $params['memo'] ?? '';
            if(isset($params['location_code'])&&isset($params['target_location_code'])){
                $location_data = DB::table('cloudhouse_warehouse_location')->where('warehouse_id',$params['warehouse_id'])->where('location_code',$params['location_code'])->select('id')->first();
                $location_data2 = DB::table('cloudhouse_warehouse_location')->where('warehouse_id',$params['warehouse_id'])->where('location_code',$params['target_location_code'])->select('id')->first();
                if(empty($location_data)){
                    return ['code' => 500, 'msg' => '原库位编码错误，请重新输入！'];
                }
                if(empty($location_data2)){
                    return ['code' => 500, 'msg' => '目标库位编码错误，请重新输入！'];
                }
                $params['location_id'] = $location_data->id;
                $params['target_location_id'] = $location_data2->id;
            }
            foreach ($params['items'] as $item){
                // 下架 扣减原库位库存
                $locationStock = db::table('cloudhouse_location_num')
                    ->where('location_id', $params['location_id'])
                    ->where('custom_sku_id', $item['custom_sku_id'])
                    ->where('platform_id', $params['platform_id'])
                    ->first();
                $num = $locationStock->num - $item['move_num'];
                $locationStock = db::table('cloudhouse_location_num')
                    ->where('location_id', $params['location_id'])
                    ->where('custom_sku_id', $item['custom_sku_id'])
                    ->where('platform_id', $params['platform_id'])
                    ->update(['num' => $num]);
                // 下架日志
                $this->saveCloudhouseLocationLog($params['location_id'], 2, $item['move_num'], $item['custom_sku_id'], $num, $params['user_id'], $params['platform_id'], '', 0, '库位库存移动下架，'. $memo);
                // 上架 增加目标库位库存
                $superior = db::table('cloudhouse_location_num')
                    ->where('location_id', $params['target_location_id'])
                    ->where('custom_sku_id', $item['custom_sku_id'])
                    ->where('platform_id', $params['target_platform_id'])
                    ->first();
                if ($superior){
                    $num = $item['move_num'] + $superior->num;
                    $superior = db::table('cloudhouse_location_num')
                        ->where('location_id', $params['target_location_id'])
                        ->where('custom_sku_id', $item['custom_sku_id'])
                        ->where('platform_id', $params['target_platform_id'])
                        ->update(['num' => $num]);
                }else{
                    $superior = db::table('cloudhouse_location_num')
                        ->insertGetId([
                            'custom_sku' => $item['custom_sku'],
                            'custom_sku_id' => $item['custom_sku_id'],
                            'spu' => $item['spu'],
                            'spu_id' => $item['spu_id'],
                            'num' => $item['move_num'],
                            'lock_num' => 0,
                            'location_id' => $params['target_location_id'],
                            'platform_id' => $params['target_platform_id']
                        ]);
                }
                // 上架日志
                $this->saveCloudhouseLocationLog($params['target_location_id'], 1, $item['move_num'], $item['custom_sku_id'], $num, $params['user_id'], $params['target_platform_id'], '', 0,'库位库存移动上架，'. $memo);
//                // 保存日志
//                $this->saveCloudhouseLocationLog($params['location_id'], 4, $item['move_num'], $item['custom_sku_id'], $num, $params['user_id'], '', $params['target_location_id'], '库位库存移动');
            }

            db::commit();
            return ['code' => 200, 'msg' => '库存转移成功！'];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => '库存转移失败！错误原因：'.$e->getMessage().'；错误位置：'.$e->getLine()];
        }
    }

    public function _checkMoveWarehouseLocationInventoty($params)
    {
        if(isset($params['location_id']) && !empty($params['location_id'])){
            $locationMdl = db::table('cloudhouse_warehouse_location')->where('id', $params['location_id'])->first();
            if (empty($locationMdl)){
                throw new \Exception('未查询到原始库位信息！');
            }
            if(isset($params['target_location_id']) && !empty($params['target_location_id'])){
                $targetLocationMdl = db::table('cloudhouse_warehouse_location')->where('id', $params['target_location_id'])->first();
                if (empty($targetLocationMdl)){
                    throw new \Exception('未查询到目标库位的信息！');
                }
                if ($targetLocationMdl->level != 3){
                    throw new \Exception('目标库位只能为三级库位！');
                }
            }elseif(isset($params['target_location_code']) && !empty($params['target_location_code'])){
                throw new \Exception('未给定目标库位编码！');
            }else{
                throw new \Exception('未给定目标库位信息！');
            }
            if($locationMdl->warehouse_id != $targetLocationMdl->warehouse_id){
                throw new \Exception('原始库位所在仓库与目标库位所在仓库不一致！');
            }

            if(!isset($params['platform_id']) || empty($params['platform_id'])){
                throw new \Exception('未给定原始平台标识！');
            }
            if(!isset($params['target_platform_id']) || empty($params['target_platform_id'])){
                throw new \Exception('未给定目标平台标识！');
            }

            if ($params['location_id'] == $params['target_location_id']){
                if ($params['platform_id'] == $params['target_platform_id']){
                    throw new \Exception('无效的库位库存转移操作!');
                }
            }
        }elseif(isset($params['location_code']) && !empty($params['location_code'])){
            if(!isset($params['warehouse_id'])){
                throw new \Exception('未获取到仓库信息！');
            }
            $locationMdl = db::table('cloudhouse_warehouse_location')->where('location_code', $params['location_code'])->where('warehouse_id',$params['warehouse_id'])->first();
            if (empty($locationMdl)){
                throw new \Exception('未查询到原始库位信息！');
            }else{
                $params['location_id'] = $locationMdl->id;
            }
            if(isset($params['target_location_code']) && !empty($params['target_location_code'])){
                $targetLocationMdl = db::table('cloudhouse_warehouse_location')->where('location_code', $params['target_location_code'])->where('warehouse_id',$params['warehouse_id'])->first();
                if (empty($targetLocationMdl)){
                    throw new \Exception('未查询到目标库位的信息！');
                }else{
                    $params['target_location_id'] = $targetLocationMdl->id;
                }
                if ($targetLocationMdl->level != 3){
                    throw new \Exception('目标库位只能为三级库位！');
                }
            }else{
                throw new \Exception('未给定目标库位信息！');
            }
            if($locationMdl->warehouse_id != $targetLocationMdl->warehouse_id){
                throw new \Exception('原始库位所在仓库与目标库位所在仓库不一致！');
            }

            if(!isset($params['platform_id']) || empty($params['platform_id'])){
                throw new \Exception('未给定原始平台标识！');
            }
            if(!isset($params['target_platform_id']) || empty($params['target_platform_id'])){
                throw new \Exception('未给定目标平台标识！');
            }
            if ($params['location_id'] == $params['target_location_id']){
                if ($params['platform_id'] == $params['target_platform_id']){
                    throw new \Exception('无效的库位库存转移操作!');
                }
            }
        }else{
            throw new \Exception('未给定原始库位标识！');
        }

        if(!isset($params['user_id']) || empty($params['user_id'])){
            throw new \Exception('未给定操作人标识！');
        }

        if (isset($params['items']) && !empty($params['items'])){
            $locationNum  = db::table('cloudhouse_location_num')
                ->where('location_id', $params['location_id'])
                ->where('platform_id', $params['platform_id'])
                ->get();
            foreach ($params['items'] as &$item){
                $customSkuMdl = db::table('self_custom_sku')
                    ->where('custom_sku', $item['custom_sku'])
                    ->orWhere('old_custom_sku', $item['custom_sku'])
                    ->first();
                if (empty($customSkuMdl)){
                    throw new \Exception('库存sku不正确！');
                }
                if (!isset($item['move_num']) && $item['move_num'] <= 0) {
                    throw new \Exception('移动库存数量不正确！');
                }
                $error = '';
                foreach ($locationNum as $v){
                    if ($v->custom_sku_id == $customSkuMdl->id){
                        $lockNum = $this->GetLocationCustomSkuLockNum($v->custom_sku_id, $params['location_id'], 0, $params['platform_id']);
                        $lockNum = array_sum(array_column($lockNum, 'lock_num'));
                        $num = $v->num - $lockNum;
                        if ($item['move_num'] > $num){
                            $error .= '库位编码：'.$locationMdl->location_code.'，库存sku：'.$item['custom_sku'].'库存不足！原始库位数量为'.$v->num.'；已锁定数量为：'.$lockNum.'；实际可转移数量为'.$num.';本次需转移数量为'.$item['move_num'].'；差额为'.($item['move_num']-$num).'；';
                        }
                    }
                }
                if ($error){
                    throw new \Exception($error);
                }
                $item['custom_sku_id'] = $customSkuMdl->id;
                $item['spu'] = $customSkuMdl->spu;
                $item['spu_id'] = $customSkuMdl->spu_id;
            }
        }else{
            throw new \Exception('未给定移动库存详情数据！');
        }

        return $params;
    }

    public function updateCloudhouseWarehouseProperty()
    {
        try {
            $customSkuMdl = db::table('self_custom_sku as a')
                ->leftJoin('self_spu as b', 'a.spu_id', '=', 'b.id')
                ->get(['a.*', 'b.base_spu_id']);
            $totalPrice = [
                'ta' => 0, // 同安仓
                'qz' => 0, // 泉州仓
                'yc' => 0, // 云仓
                'gcxnc' => 0, // 工厂虚拟仓
                'gcjcc' => 0, // 工厂寄存仓
                'gczfc' => 0, // 工厂直发仓
                'szjcc' => 0, // 深圳寄存仓
            ];
            $error = '';
            $priceMdl = db::table('inventory_total_pirce')->get();
            $spuColorMdl = db::table('self_spu_info')->get();
            $customSkuPrice = [];
            foreach ($priceMdl as $p){
                $key = $p->custom_sku_id.'-'.$p->warehouse_id;
                if (!array_key_exists($key, $customSkuPrice)){
                    $customSkuPrice[$key] = $p->price;
                }
            }
            $baseSpuPrice = [];
            foreach ($spuColorMdl as $b){
                $key = $b->base_spu_id;
                if (!array_key_exists($key, $baseSpuPrice)){
                    $baseSpuPrice[$key] = $b->unit_price;
                }
            }
            foreach ($customSkuMdl as $v){
                $price_1 = $customSkuPrice[$v->id.'-'.'1'] ?? 0;
                if ($price_1 == 0){
                    $price_1 = $baseSpuPrice[$v->base_spu_id] ?? 0;
                    if ($price_1 == 0){
                        $error .= $v->id.',';
                    }else{
                        $totalPrice['ta'] += $price_1 * $v->tongan_inventory;
                    }
                }else{
                    $totalPrice['ta'] += $price_1;
                }


                $price_2 = $customSkuPrice[$v->id.'-'.'2'] ?? 0;
                if ($price_2 == 0){
                    $price_2 = $baseSpuPrice[$v->base_spu_id] ?? 0;
                    if ($price_2 == 0){
                        $error .= $v->id.',';
                    }else{
                        $totalPrice['qz'] += $price_2 * $v->quanzhou_inventory;
                    }
                }else{
                    $totalPrice['qz'] += $price_2;
                }


                $price_3 = $customSkuPrice[$v->id.'-'.'3'] ?? 0;
                if ($price_3 == 0){
                    $price_3 = $baseSpuPrice[$v->base_spu_id] ?? 0;
                    if ($price_3 == 0){
                        $error .= $v->id.',';
                    }else{
                        $totalPrice['yc'] += $price_3 * $v->cloud_num;
                    }
                }else{
                    $totalPrice['yc'] += $price_3;
                }


                $price_4 = $customSkuPrice[$v->id.'-'.'4'] ?? 0;
                if ($price_4 == 0){
                    $price_4 = $baseSpuPrice[$v->base_spu_id] ?? 0;
                    if ($price_4 == 0){
                        $error .= $v->id.',';
                    }else{
                        $totalPrice['gcxnc'] += $price_4 * $v->factory_num;
                    }
                }else{
                    $totalPrice['gcxnc'] += $price_4;
                }


                $price_6 = $customSkuPrice[$v->id.'-'.'6'] ?? 0;
                if ($price_6 == 0){
                    $price_6 = $baseSpuPrice[$v->base_spu_id] ?? 0;
                    if ($price_6 == 0){
                        $error .= $v->id.',';
                    }else{
                        $totalPrice['gcjcc'] += $price_6 * $v->deposit_inventory;
                    }
                }else{
                    $totalPrice['gcjcc'] += $price_6;
                }

                $price_22 = $customSkuPrice[$v->id.'-'.'22'] ?? 0;
                if ($price_22 == 0){
                    $price_22 = $baseSpuPrice[$v->base_spu_id] ?? 0;
                    if ($price_22 == 0){
                        $error .= $v->id.',';
                    }else{
                        $totalPrice['gczfc'] += $price_22 * $v->direct_inventory;
                    }
                }else{
                    $totalPrice['gczfc'] += $price_22;
                }


                $price_23 = $customSkuPrice[$v->id.'-'.'23'] ?? 0;
                if ($price_23 == 0){
                    $price_23 = $baseSpuPrice[$v->base_spu_id] ?? 0;
                    if ($price_23 == 0){
                        $error .= $v->id.',';
                    }else{
                        $totalPrice['szjcc'] += $price_23 * $v->shenzhen_inventory;
                    }
                }else{
                    $totalPrice['szjcc'] += $price_23;
                }
            }
            $skuId = implode(',', array_unique(explode(',', $error)));

            $warehouseId = [
                'ta' => 1, // 同安仓
                'qz' => 2, // 泉州仓
                'yc' => 3, // 云仓
                'gcxnc' => 4, // 工厂虚拟仓
                'gcjcc' => 6, // 工厂寄存仓
                'gczfc' => 22, // 工厂直发仓
                'szjcc' => 23, // 深圳寄存仓
            ];
            db::beginTransaction();
            foreach ($totalPrice as $k => $v){
                $update = db::table('cloudhouse_warehouse')->where('id', $warehouseId[$k])->update(['total_price' => $v]);
            }
            db::commit();
            return ['code' => 200, 'msg' => '仓库资产更新成功！', 'data' => ['res' => $totalPrice, 'error' => $skuId]];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => '仓库资产更新失败！错误原因：'.$e->getMessage().'；错误位置：'.$e->getLine()];
        }
    }

    //平台库存列表导入查询
    public function PlatformInventoryExcelImport($params)
    {
        $p['row'] = ['custom_sku','num'];
        $p['file'] = $params['file'];
        $p['start'] = 2;
        $platform_id = $params['platform_id'];
        $warehouse_id = $params['warehouse_id'];

        $data =  $this->CommonExcelImport($p);
        $sku_ids = [];
        $sku_res = [];
        foreach ($data as $v) {
            # code...
            if(!empty($v['custom_sku'])){
                $sku_id = $this->GetCustomSkuId($v['custom_sku']);
                $sku_ids[] = $sku_id;
                $sku_res[$sku_id] = $v['num'];
            }
        }

             
        $data = $this->getPlatformInventoryList(['sku_ids'=>$sku_ids,'sku_res'=>$sku_res,'platform_id'=>$platform_id,'warehouse_id'=>$warehouse_id]);

      
        return ['msg'=>'导入成功','type'=>'success','data'=>$data];

    }

   //excel平台库存列表查询
    public function ExcelPlatformInventoryList($params)
    {


        $p['row'] = ['custom_sku'];
        $p['file'] = $params['file'];
        $p['start'] = 2;
        $data =  $this->CommonExcelImport($p);
        $err = [];
        $custom_sku_ids = [];
        foreach ($data as $v) {
            # code...
            if(isset($v['custom_sku'])){

                $custom_sku_id = $this->GetCustomSkuId($v['custom_sku']);
                if($custom_sku_id>0){
                    $custom_sku_ids[] = $custom_sku_id;
                }else{
                    $err[] = $v['custom_sku'];
                }
            }
        }

        if(count($err)>0){
            return ['type'=>'fail','msg'=>'无此库存sku'.implode(',',$err)];
        }

        $data = $this->getPlatformInventoryList(['custom_sku_ids'=>$custom_sku_ids,'token'=>$params['token']]);
        $data['type']='success';
        return $data;

    }
    //平台库存列表
    public function getPlatformInventoryList($params)
    {
        $postType = $params['posttype'] ?? 1;
        $pagenum  = isset($params['page']) ? $params['page'] : 1;
        $limit    = isset($params['limit']) ? $params['limit'] : 30;

        $page = $pagenum - 1;
        if ($page != 0) {
            $page = $page * $limit;
        }

        $query = db::table('cloudhouse_location_num as a')
            ->leftjoin('cloudhouse_warehouse_location as b', 'a.location_id', '=', 'b.id')
            ->leftJoin('self_custom_sku as c', 'a.custom_sku_id', '=', 'c.id')
            ->leftJoin('self_color_size as d', 'c.size', '=', 'd.identifying')
            ->select('a.*', 'b.warehouse_id', 'c.img', 'd.sort','b.type');

        if (isset($params['platform_id']) && !empty($params['platform_id'])) {
            $query->where('a.platform_id', $params['platform_id']);
        }

        if(isset($params['sku_ids'])){
            $query->whereIn('c.id', $params['sku_ids']);
        }

        if (isset($params['warehouse_id']) && !empty($params['warehouse_id'])) {
            if(is_array($params['warehouse_id'])){
                $query->whereIn('b.warehouse_id', $params['warehouse_id']);
            }else{
                $query->where('b.warehouse_id', $params['warehouse_id']);
            }

        }

        if (isset($params['custom_sku']) && !empty($params['custom_sku'])){
            $customSkuIds = db::table('self_custom_sku')
                ->where('custom_sku', 'like', '%' . $params['custom_sku'] . '%')
                ->orWhere('old_custom_sku', 'like', '%' . $params['custom_sku'] . '%')
                ->pluck('id');

            if ($customSkuIds->isEmpty()) {
                return $this->emptyList();
            }

            $query->whereIn('a.custom_sku_id', $customSkuIds);
        }

        if (isset($params['custom_skus']) && !empty($params['custom_skus'])) {
            $customSkuArr   = explode(',', $params['custom_skus']);
            $customSkuIdArr = [];
            foreach ($customSkuArr as $customSku) {
                $customSkuId = DB::table('self_custom_sku')
                    ->where('custom_sku', $customSku)
                    ->orwhere('old_custom_sku', $customSku)
                    ->value('id');
                if ($customSkuId) {
                    $customSkuIdArr[] = $customSkuId;
                }
            }

            if (!$customSkuIdArr) {
                return $this->emptyList();
            }

            $query->whereIn('a.custom_sku_id', $customSkuIdArr);
        }


        if(isset($params['custom_sku_ids'])){
            $query->whereIn('a.custom_sku_id', $params['custom_sku_ids']);
            $params['is_zero']=1;
            $postType = 2;
            $params['find_user_id'] = $this->GetUserIdByToken($params['token']);
        }

        if(isset($params['is_zero']) && !empty($params['is_zero'])){
            if($params['is_zero']==1){
                $query = $query->where('a.num','>',0);
            }
        }
        if (isset($params['spu']) && !empty($params['spu'])){
            if (is_array($params['spu'])) {
                $query->whereIn('a.spu_id', $params['spu']);
            } else {
                $spuIds = db::table('self_spu')
                    ->where(function($q) use ($params){
                        foreach ($params['spu'] as $spu){
                            $q->orWhere('spu', 'like', '%'.$spu.'%')
                                ->orwhere('old_spu', 'like', '%'.$spu.'%');
                        }
                        return $q;
                    })
                    ->pluck('id');

                if ($spuIds->isEmpty()) {
                    return $this->emptyList();
                }
                $query->whereIn('a.spu_id', $spuIds);
            }
        }

        if(isset($params['one_cate_id'])){
            $spuIds2 = db::table('self_spu')->whereIn('one_cate_id',$params['one_cate_id'])->pluck('id');
            if ($spuIds2->isEmpty()) {
                return $this->emptyList();
            }
            $query->whereIn('a.spu_id', $spuIds2);
        }
        if(isset($params['two_cate_id'])){
            $spuIds3 = db::table('self_spu')->whereIn('two_cate_id',$params['two_cate_id'])->pluck('id');
            if ($spuIds3->isEmpty()) {
                return $this->emptyList();
            }
            $query->whereIn('a.spu_id', $spuIds3);
        }
        if(isset($params['three_cate_id'])){
            $spuIds4 = db::table('self_spu')->whereIn('three_cate_id',$params['three_cate_id'])->pluck('id');
            if ($spuIds4->isEmpty()) {
                return $this->emptyList();
            }
            $query->whereIn('a.spu_id', $spuIds4);
        }

//        if ($params['token'] == '69282C1B5216E0F401A7640DDB46C936'){
//            $query->orderBy('d.sort', 'ASC');
//        }
        if (isset($customSkuIdArr)) {
            $customSkuIdStr = implode(',', $customSkuIdArr);
            $query->orderByRaw("find_in_set(a.custom_sku_id, '{$customSkuIdStr}')");
        }
        $query->orderBy('d.sort', 'ASC');

        $list = $query->get();


        // if ($list->isEmpty()) {
        //     return $this->emptyList();
        // }

        $result = [];
        $inventorySum = 0;
        foreach ($list as $v) {
            if($v->type==2) {
                $v->bad_num = $v->num;
            }else{
                $v->bad_num = 0;
            }

            $inventorySum += $v->num;
            $key = $v->platform_id . $v->warehouse_id . '-' . $v->custom_sku_id;

            if (isset($result[$key])) {
                $result[$key]->num += $v->num;
                if($v->type==2) {
                    $result[$key]->bad_num += $v->num;
                }
            } else {
                $result[$key] = $v;
            }

            $location_ids['location_id'] = $v->location_id;
            $location_ids['location_name'] = $this->Getlocation($v->location_id)['location_code']; 
            if($v->type==1) {
                $location_ids['num'] = $v->num;
            }
            
            $result[$key]->location_ids[] = $location_ids;
//            if ($params['token'] == '64E69B7238C7E6480322EC4BE6FBAAA1'){
//                var_dump($v);
//            }
        }

        $count = count($result);

        if ($postType != 2 && !isset($params['sku_ids'])) {
            $result = array_slice($result, $page, $limit); // 默认第一页，显示30条
        }


        $platformMdl = db::table('platform')->pluck('name', 'id');

        $spu_ids = [];
        $custom_sku_ids = [];
        $warehouse_ids = [];
        $platform_ids = [];
        foreach ($result as $st){
            if(!in_array($st->spu_id,$spu_ids)){
                $spu_ids[] = $st->spu_id;
            }
            if(!in_array($st->custom_sku_id,$custom_sku_ids)){
                $custom_sku_ids[] = $st->custom_sku_id;
            }
            if(!in_array($st->warehouse_id,$warehouse_ids)){
                $warehouse_ids[] = $st->warehouse_id;
            }
            if(!in_array($st->platform_id,$platform_ids)){
                $platform_ids[] = $st->platform_id;
            }
        }


        $spuList = db::table('self_spu')->select('id', 'spu', 'old_spu')->whereIn('id', $spu_ids)->get()->keyBy('id');
        $customSkuList = db::table('self_custom_sku')
            ->select('id', 'custom_sku', 'old_custom_sku')
            ->whereIn('id', $custom_sku_ids)
            ->get()
            ->keyBy('id');

        $inventoryDetail = $this->batchinventoryDetailByWlp($custom_sku_ids, $warehouse_ids, [], $platform_ids);


        foreach ($result as $v) {
            $v->spu            = $spuList[$v->spu_id]->old_spu ?: $spuList[$v->spu_id]->spu;
            $v->custom_sku     = $customSkuList[$v->custom_sku_id]->old_custom_sku ?: $customSkuList[$v->custom_sku_id]->custom_sku;
            $v->new_custom_sku = $customSkuList[$v->custom_sku_id]->custom_sku;
            $v->platform_name  = $platformMdl[$v->platform_id] ?? '';
            $inventory         = $inventoryDetail[$v->custom_sku_id . '_' . $v->warehouse_id . '_' . $v->platform_id] ??
                ['shelf_num' => 0, 'lock_num' => 0, 'delist_num' => 0,];
            $v->intsock_num    = $v->num - $inventory['lock_num'] - $v->bad_num;//可用库存
            $v->lock_num       = $inventory['lock_num'];//锁定库存
            $v->shelf_num      = $inventory['shelf_num'];//待入库库存
            $v->delist_num     = $inventory['delist_num'];//已拣货库存
            $v->warehouse_name = $this->GetWarehouse($v->warehouse_id)['warehouse_name'];
            $v->img = $this->GetCustomskuImg($v->custom_sku);

            $v->move_num = 0;
            if(isset($params['sku_res'][$v->custom_sku_id])){
                $v->move_num = (int)$params['sku_res'][$v->custom_sku_id];
            }
        }

        if($postType==2){
            $p['title']='国家库存导出表'.time();
            $list = [
                'platform_name'  => '国家',
                'platform_identifying'  => '国家标识',
                'warehouse_name' => '仓库',
                'custom_sku'     => '库存SKU	',
                'spu'            => 'spu',
                'num'            => '库存',
                'shelf_num'      => '待入库库存',
            ];

            $p['title_list']  = $list;
            $p['data'] =  $result;
            $find_user_id = $params['find_user_id']??1;
            $p['user_id'] = $find_user_id;
            $p['type'] = '库存管理-国家库存导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }

        return ['count' => $count, 'list' => array_values($result),'inventorySum'=>$inventorySum];
    }

    private function emptyList()
    {
        return ['count' => 0, 'list' => []];
    }

    public function getInventoryDetailList($params)
    {
        try {
            $list = db::table('cloudhouse_location_num as a')
                ->leftJoin('cloudhouse_warehouse_location as b', 'a.location_id', '=', 'b.id')
                ->leftJoin('cloudhouse_warehouse as c', 'b.warehouse_id', '=', 'c.id')
                ->leftJoin('platform as d', 'a.platform_id', '=', 'd.Id');
            if (isset($params['custom_sku_id']) && !empty($params['custom_sku_id'])){
                $list = $list->where('a.custom_sku_id', $params['custom_sku_id']);
            }
            if (isset($params['platform_id']) && !empty($params['platform_id'])){
                $list = $list->where('a.platform_id', $params['platform_id']);
            }
            if (isset($params['location_id']) && !empty($params['location_id'])){
                $list = $list->where('a.location_id', $params['location_id']);
            }
            if (isset($params['page']) || isset($params['limit'])){
                $limit = $params['limit'] ?? 30;
                $page = $params['page'] ?? 1;
                $offset = $limit * ($page - 1);
                $list = $list->limit($limit)->offset($offset);
            }
            $count = $list->count();
            $list = $list->get(['a.*', 'b.location_code', 'c.warehouse_name', 'b.location_name', 'd.name as platform_name']);
            foreach ($list as $v){
                $inventory      = $this->inventoryDetailByWlp($v->custom_sku_id, 0, $v->location_id, $v->platform_id);
                $v->intsock_num = $v->num - $inventory['lock_num'] - $inventory['shelf_num'];//可用库存
                $v->lock_num    = $inventory['lock_num'];//锁定库存
                $v->shelf_num   = $inventory['shelf_num'];//待入库库存
                $v->delist_num  = $inventory['delist_num'];//已拣货库存
            }
            return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $list]];
        }catch (\Exception $e){

        }
    }

    public function getLocationInfo($params)
    {
        $locationMdl = db::table('cloudhouse_warehouse_location as a')
            ->leftJoin('cloudhouse_warehouse as b', 'a.warehouse_id', '=', 'b.id')
            ->where('a.warehouse_id', $params['warehouse_id'])
            ->where('a.location_code', $params['location_code'])
            ->select('a.*', 'a.id as location_id', 'b.warehouse_name')
            ->first();
        if (empty($params)){
            throw new \Exception('未查询到库位信息！');
        }

        return ['data' => $locationMdl];
    }
}